import { View, Text, Image } from "@tarojs/components";
import ico_add_three from "@/assets/image/ico_add_three.svg";
import { useEffect, useRef, useState } from "react";
import SingleAd from "./SingleAd";
import { deleteAd, getAdList } from "@/services/entities/all";

const InitBanner = () => {
  const [adList, setAdList] = useState<any>([]);
  const adListRef = useRef<any[]>([]);

  const getList = () => {
    getAdList().then((res: any) => {
      console.log("res", res);
      const list = res
        ? res.map((item) => {
            return {
              ...item,
              isAdded: true,
              imageUrl: item.imageUrl?.split(",") ?? [],
            };
          })
        : [];
      adListRef.current = list;
      setAdList(list);
    });
  };

  useEffect(() => {
    getList();
  }, []);

  const addNew = () => {
    const temp = [...adList];
    const newAd = {
      isOpen: false,
      imageUrl: [],
      videoUrl: "",
      storeName: "",
      storeId: "",
      isAdded: false,
    };
    temp.push(newAd);
    adListRef.current.push(newAd);
    setAdList(temp);
  };
  const onDelete = (index, id, isAdded) => {
    const deleteIndex = () => {
      const temp = [...adList];
      temp.splice(index, 1);
      adListRef.current.splice(index, 1);
      setAdList(temp);
    };
    if (!isAdded) {
      deleteIndex();
      return;
    }
    deleteAd({ id }).then(() => {
      deleteIndex();
    });
  };

  const onAdChange = (value, index) => {
    adListRef.current[index] = value;
    console.log(adListRef.current);
  };

  return (
    <View className="bg-page pb-100">
      {adList?.map((item, index) => {
        const refItem = adListRef.current[index];
        console.log("refItem", refItem);
        return (
          <SingleAd
            key={index}
            onDelete={() => {
              onDelete(index, item.id, item.isAdded);
            }}
            onAdd={() => {
              getList();
            }}
            onChange={(value) => {
              onAdChange(value, index);
            }}
            initValue={{
              isOpen: refItem.isOpen,
              imageUrl: refItem.imageUrl,
              videoUrl: refItem.videoUrl,
              storeId: refItem.storeId,
              storeName: refItem.storeName,
            }}
            isAdded={refItem.isAdded}
          />
        );
      })}
      <View className="bottom pd-20  dis-flex align-center border-box">
        <View
          className="flex-1 flex-center pd-tb-20 border-box bg-007DDB br-8 fs-28 lh-38 cl-white"
          onClick={addNew}
        >
          <Image src={ico_add_three} className="img-36 mr-8" />
          <Text>新增</Text>
        </View>
      </View>
    </View>
  );
};

export default InitBanner;
